package com.itheima.algorithm.dynamicprogramming;

import java.util.Arrays;

/**
 * <h3>零钱兑换 - 动态规划</h3>
 * <p>凑成总金额的凑法中，需要硬币最少个数是几？</p>
 */
public class ChangeMakingProblemLeetcode322 {

    /*
        二维数组
     */
    public int coinChange(int[] coins, int amount) {
        int[][] dp = new int[coins.length][amount + 1];
        for (int j = 1; j < amount + 1; j++) {
            if (j >= coins[0]) { // 放下
                dp[0][j] = dp[0][j - coins[0]] + 1;
            } else { // 放不下
                dp[0][j] = amount + 1;
            }
        }
        for (int i = 1; i < coins.length; i++) {
            for (int j = 1; j < amount + 1; j++) {
                if (j >= coins[i]) { // 放下
                    dp[i][j] = Integer.min(dp[i - 1][j], dp[i][j - coins[i]] + 1);
                } else { // 放不下
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        int r = dp[coins.length - 1][amount];
        return r > amount ? -1 : r;
    }

    /*
        一维数组
     */
    public int coinChange2(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        for (int j = 1; j < amount + 1; j++) {
            if (j >= coins[0]) { // 放下
                dp[j] = dp[j - coins[0]] + 1;
            } else { // 放不下
                dp[j] = amount + 1;
            }
        }
        System.out.println(Arrays.toString(dp));
        for (int i = 1; i < coins.length; i++) {
            for (int j = 1; j < amount + 1; j++) {
                if (j >= coins[i]) { // 放下
                    dp[j] = Integer.min(dp[j], dp[j - coins[i]] + 1);
                }
            }
            System.out.println(Arrays.toString(dp));
        }
        int r = dp[amount];
        return r > amount ? -1 : r;
    }

    /*
        一维数组（优化）
     */
    public int coinChange3(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        dp[0] = 0;
        System.out.println(Arrays.toString(dp));
        for (int coin : coins) {
            for (int j = coin; j < amount + 1; j++) {
                dp[j] = Integer.min(dp[j], dp[j - coin] + 1);
            }
            System.out.println(Arrays.toString(dp));
        }
        int r = dp[amount];
        return r > amount ? -1 : r;
    }

    public static void main(String[] args) {
        ChangeMakingProblemLeetcode322 leetcode = new ChangeMakingProblemLeetcode322();
        int count = leetcode.coinChange3(new int[]{5, 2, 1}, 5);
//        int count = leetcode.coinChange(new int[]{25, 10, 5, 1}, 41);
//        int count = leetcode.coinChange(new int[]{2}, 3);
//        int count = leetcode.coinChange(new int[]{15, 10, 1}, 21);
        System.out.println(count);
    }
}
